<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>案例-图书管理</title>
  <!-- 字体图标 -->
  <link rel="stylesheet" href="https://at.alicdn.com/t/c/font_3736758_vxpb728fcyh.css">
  <!-- 引入bootstrap.css -->
  <!-- <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.3.3/css/bootstrap.min.css" rel="stylesheet"> -->
  <link href="./css/bootstrap.min.css" rel="stylesheet">
  <!-- 核心样式 -->
  <link rel="stylesheet" href="./css/index.css">
</head>

<body>
  <!-- 主体区域 -->
  <div class="container">
    <!-- 头部标题和添加按钮 -->
    <div class="top">
      <h3>图书管理</h3>
      <button type="button" class="btn btn-primary plus-btn" data-bs-toggle="modal" data-bs-target=".add-modal">
        +添加
      </button>
    </div>

    <!-- 数据列表 -->
    <table class="table">
      <thead class="table-light">
        <tr>
          <th style="width: 150px;">序号</th>
          <th>书名</th>
          <th>作者</th>
          <th>出版社</th>
          <th style="width: 180px;">操作</th>
        </tr>
      </thead>
      <tbody class="list">

        <!-- <tr>
          <td>1</td>
          <td>JavaScript程序设计</td>
          <td>马特·弗里斯比</td>
          <td>人民邮电出版社</td>
          <td>
            <span class="del">删除</span>
            <span class="edit">编辑</span>
          </td>
        </tr> -->

      </tbody>
    </table>

  </div>
  <!-- 新增-弹出框 -->
  <div class="modal fade add-modal">
    <!-- 中间白色区域 -->
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header top">
          <span>添加图书</span>
          <button type="button" class="btn-close" aria-label="Close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body form-wrap">
          <!-- 新增表单 -->
          <form class="add-form">
            <div class="mb-3">
              <label for="bookname" class="form-label">书名</label>
              <input type="text" class="form-control bookname" placeholder="请输入书籍名称" name="bookname">
            </div>
            <div class="mb-3">
              <label for="author" class="form-label">作者</label>
              <input type="text" class="form-control author" placeholder="请输入作者名称" name="author">
            </div>
            <div class="mb-3">
              <label for="publisher" class="form-label">出版社</label>
              <input type="text" class="form-control publisher" placeholder="请输入出版社名称" name="publisher">
            </div>
          </form>
        </div>
        <div class="modal-footer btn-group">
          <button type="button" class="btn btn-primary" data-bs-dismiss="modal"> 取消 </button>
          <button type="button" class="btn btn-primary add-btn"> 保存 </button>
        </div>
      </div>
    </div>
  </div><!-- /.modal -->

  <!-- 编辑-弹出框 -->
  <div class="modal fade edit-modal">
    <!-- 中间白色区域 -->
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header top">
          <span>编辑图书</span>
          <button type="button" class="btn-close" aria-label="Close" data-bs-dismiss="modal"></button>
        </div>
        <div class="modal-body form-wrap">
          <!-- 编辑表单 -->
          <form class="edit-form">
            <input type="hidden" class="id" name="id">
            <div class="mb-3">
              <label for="bookname" class="form-label">书名</label>
              <input type="text" class="form-control bookname" placeholder="请输入书籍名称" name="bookname">
            </div>
            <div class="mb-3">
              <label for="author" class="form-label">作者</label>
              <input type="text" class="form-control author" placeholder="请输入作者名称" name="author">
            </div>
            <div class="mb-3">
              <label for="publisher" class="form-label">出版社</label>
              <input type="text" class="form-control publisher" placeholder="请输入出版社名称" name="publisher">
            </div>
          </form>
        </div>
        <div class="modal-footer btn-group">
          <button type="button" class="btn btn-primary" data-bs-dismiss="modal"> 取消 </button>
          <button type="button" class="btn btn-primary edit-btn"> 修改 </button>
        </div>
      </div>
    </div>
  </div><!-- /.modal -->


  <!-- <script src="https://cdn.bootcdn.net/ajax/libs/axios/1.2.0/axios.min.js"></script> -->
  <script src="./lib/axios.min.js"></script>
  <script src="./lib/form-serialize.js"></script>
  <!-- <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/js/bootstrap.min.js"></script> -->
  <script src="./lib/bootstrap.min.js"></script>
  <!-- 核心逻辑 -->

  <script>
    /**
     * 目标1：渲染图书列表
     *  1.1 获取数据
     *  1.2 渲染数据
     */
    const creator = "king";
    function getBooksList() {
      //  1.1 获取数据
      axios({
        url: "https://hmajax.itheima.net/api/books",
        params: {
          creator: creator
        }
      }).then(res => {
        // console.log(res);
        const bookList = res.data.data;
        // 1.2 渲染数据
        const htmlStr = bookList.map((item, index) => {
          return `<tr>
            <td>${index + 1}</td>
            <td>${item.bookname}</td>
            <td>${item.author}</td>
            <td>${item.publisher}</td>
            <td data-id=${item.id}>
              <span class="del">删除</span>
              <span class="edit">编辑</span>
            </td>
          </tr>`
        }).join('')
        // console.log(htmlStr);
        document.querySelector(".list").innerHTML = htmlStr;
      })

    }
    // 网页加载运行，获取并渲染列表一次
    getBooksList();



    /**
      * 目标2：新增图书
      *  2.1 新增弹框->显示和隐藏
      *  2.2 收集表单数据，并提交到服务器保存
      *  2.3 刷新图书列表
   */
    //  2.1 新增弹框->显示和隐藏
    const addModalDom = document.querySelector(".add-modal")
    const addModal = new bootstrap.Modal(addModalDom)

    // 保存按钮->点击->隐藏弹框
    document.querySelector(".add-btn").addEventListener("click", function () {
      // 2.2 收集表单数据，并提交到服务器保存
      const addForm = document.querySelector(".add-form")
      console.log(addForm);
      const bookObj = serialize(addForm, { hash: true, empty: true })
      console.log(bookObj);
      // 提交到服务器a
      axios({
        url: "https://hmajax.itheima.net/api/books",
        method: "post",
        data: {
          ...bookObj,
          creator
        }
      }).then(res => {
        console.log(res);
        // 2.3 刷新图书列表
        getBooksList();
        // 重置表单
        addForm.reset()
        // 隐藏弹框
        addModal.hide();
      })

    })



    /**
     * 目标3：删除图书
     *  3.1 删除元素绑定点击事件->获取图书id
     *  3.2 调用删除接口
     *  3.3 刷新图书列表
     */
    // 删除元素->点击（事件委托）
    document.querySelector(".list").addEventListener("click", function (event) {
      // 获取触发事件的目标元素
      console.log(event.target);
      console.log(event.target.parentNode.dataset);
      // 判断点击的是删除元素
      if (event.target.classList.contains("del")) {
        // console.log("点击删除元素");
        // 获取图书id（自定义属性id）
        const theId = event.target.parentNode.dataset.id;
        console.log(theId);
        //  3.2 调用删除接口
        axios({
          url: `https://hmajax.itheima.net/api/books/${theId}`,
          method: "DELETE"
        }).then(res => {
          console.log(res);
          // 3.3 刷新图书列表
          getBooksList();
        })
      }
    })





    /**
      * 目标4：编辑图书
      *  4.1 编辑弹框->显示和隐藏
      *  4.2 获取当前编辑图书数据->回显到编辑表单中
      *  4.3 提交保存修改，并刷新列表
      */

    //  4.1 编辑弹框->显示和隐藏
    const editModalDom = document.querySelector(".edit-modal")
    const editModal = new bootstrap.Modal(editModalDom)

    // 编辑元素->点击->弹框显示
    document.querySelector(".list").addEventListener("click", function (event) {
      if (event.target.classList.contains("edit")) {
        // 4.2 获取当前编辑图书数据->回显到编辑表单中
        const theId = event.target.parentNode.dataset.id;
        console.log(theId);
        //  3.2 调用修改接口
        axios({
          url: `https://hmajax.itheima.net/api/books/${theId}`,
          // method:"GET"
        }).then(res => {
          console.log(res);
          const bookObj = res.data.data;
          // console.log(bookObj);
          // 数据对象“属性”和标签“类名”一致
          // document.querySelector(".edit-form .bookname").value = bookObj.bookname
          // document.querySelector(".edit-form .author").value = bookObj.author
          // document.querySelector(".edit-form .publisher").value = bookObj.publisher

          const keys = Object.keys(bookObj)
          console.log(keys);//['id','bookname','author','publisher']
          keys.forEach(key => {
            document.querySelector(`.edit-form .${key}`).value = bookObj[key]
          })
        })
        d
        editModal.show()
      }
    })


    // 修改按钮->点击确定-> 调修改接口 => 隐藏弹框

    document.querySelector(".edit-btn").addEventListener("click", function (event) {
      // 4.3 提交保存修改，并刷新列表
      const editForm = document.querySelector(".edit-form")
      console.log(editForm);
      const { id, bookname, author, publisher } = serialize(editForm, { hash: true, empty: true })
      // 保存正在编辑的图书id，隐藏起来：无需让用户修改
      // <input type="hidden" class="id" name="id" value="84783">
      axios({
        url: `https://hmajax.itheima.net/api/books/${id}`,
        method: "PUT",
        data: {
          bookname: bookname,
          author: author,
          publisher: publisher,
          creator: creator
        }
      }).then(res => {
        console.log(res);
        // 2.3 刷新图书列表
        getBooksList();
        // 重置表单
        editForm.reset()
        // 隐藏弹框
        editModal.hide();
      })

    })



  </script>
</body>

</html>